﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using BrnMall.Core;
using BrnMall.Manager;
using BrnMall.Manager.Domain.Product;
using BrnMall.Services;
using QIDong.WeApp.Models;
using WeiTap.Restful;
using BrnMall.Manager.Manager.WeApp;
using BrnMall.WeiXin.Sdk;
using BrnMall.Manager.Domain.WeApp;
using BrnMall.Sdk.WeiXin;
using Newtonsoft.Json;
using BrnMall.Sdk.WeiXin.weapp;
using System.Linq;
using BrnMall.Business;
using BrnMall.Manager.Filter;
using PetaPoco;
using QIDong.WeApp.Util;

namespace QIDong.WeApp.Controllers
{
    /// <summary>
    /// 小程序审核相关流程
    /// </summary>
    public class WeAppController : WebApi
    {


        #region 小程序实例
        /// <summary>
        /// 创建店铺小程序
        /// </summary>
        /// <param name="storeId">店铺ID</param>
        /// <param name="appId">小程序模板ID</param>
        /// <returns></returns>
        public int CreateStoreApplication(int storeId, int appId)
        {
            try
            {
                var application = WeApplicationManager.GetWeApplication(appId);
                if (application == null)
                    throw new Exception("未找到对应的小程序模板");
                var storeApp = new StoreApplication
                {
                    AppId = appId,
                    AuthorizationId = 0,
                    CreateTime = DateTime.Now,
                    DevStatus = 1,
                    Logo = application.Logo,
                    Name = application.Name,
                    NeedUpdate = false,
                    StoreId = storeId,
                    TemplateId = application.TemplateId
                };
                StoreApplicationManager.AddStoreApplication(storeApp);
                return storeApp.StoreAppId;
            }
            catch (Exception e)
            {
                Trace.TraceError(e.Message);
                throw;
            }
        }
        /// <summary>
        /// 手动获取更新状态
        /// </summary>
        /// <param name="storeAppId"></param>
        /// <returns></returns>
        public BaseResult GetAuditStatus(int storeAppId)
        {
            return StoreAppReleaseManager.GetAuditStatus(storeAppId);
        }
        /// <summary>
        /// 手动获取最新一次更新状态
        /// </summary>
        /// <param name="storeAppId"></param>
        /// <returns></returns>
        public BaseResult GetLastAuditStatus(int storeAppId)
        {
            return StoreAppReleaseManager.GetLastAuditStatus(storeAppId);
        }
        /// <summary>
        /// 获取店铺绑定的小程序列表
        /// </summary>
        /// <param name="storeId">店铺ID</param>
        /// <remarks>
        /// 开发状态DevStatus,0:未知，1:待上传，2:已上传，3：待审核 4:审核结束，5:已发布
        /// </remarks>
        /// <returns></returns>
        public IList<StoreApplicationModel> GetStoreApplications(int storeId)
        {
            var list = StoreApplicationManager.GetStoreApplications(storeId);
            var result = new List<StoreApplicationModel>();
            foreach (var app in list)
            {
                var newItem = new StoreApplicationModel
                {
                    AppId = app.AppId,
                    AuditId = app.AuditId,
                    AuditInfo = app.AuditInfo,
                    AuthorizationId = app.AuthorizationId,
                    CreateTime = app.CreateTime,
                    DevStatus = app.DevStatus,
                    Logo = app.Logo,
                    Name = app.Name,
                    NeedUpdate = app.NeedUpdate,
                    ReleaseTime = app.ReleaseTime,
                    StoreAppId = app.StoreAppId,
                    StoreId = app.StoreId,
                    TemplateId = app.TemplateId,
                    UserTabBar = app.UserTabBar
                };

                var auth = AppAuthorizationManager.GetAppAuthorization(app.AuthorizationId);
                if (auth == null)
                {
                    result.Add(newItem);
                    continue;
                }
                newItem.Authorization = auth;
                if (app.DevStatus == 0 || app.DevStatus == 1 || app.DevStatus == 2
                    || app.DevStatus == 5)
                {
                    result.Add(newItem);
                    continue;
                }

                var auditStatus = (GetLastAuditStatusResponse)StoreAppReleaseManager.GetLastAuditStatus(app.StoreAppId);
                app.AuditId = auditStatus.auditid;
                switch (auditStatus.status)
                {
                    case 0:
                        app.AuditInfo = string.Empty;
                        app.DevStatus = 4;
                        break;
                    case 1:
                        app.DevStatus = 1;
                        app.AuditInfo = auditStatus.reason;
                        break;
                    case 2:
                        app.DevStatus = 3;
                        app.AuditInfo = string.Empty;
                        break;
                    default:
                        app.DevStatus = 3;
                        app.AuditInfo = string.Empty;
                        break;

                }
                newItem.AuditId = auditStatus.auditid;
                newItem.DevStatus = app.DevStatus;
                newItem.AuditInfo = app.AuditInfo;
                StoreApplicationManager.UpdateStoreApplication(app);
                result.Add(newItem);
            }
            return result;
        }
        /// <summary>
        /// 获取所有小程序分页信息
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="itemsPerpage">每页多少条</param>
        /// <param name="storeAppId">小程序编号</param>
        /// <param name="storeId">店铺ID</param>
        /// <returns></returns>
        public Page<StoreApplication> GetStoreApplicationsPage(long page=1, long itemsPerpage=15, int storeAppId = 0,
            int storeId = 0)
        {
            var filter = new StoreApplicatioinFilter();
            if (storeAppId > 0)
                filter.StoreAppId = storeAppId;
            if (storeId > 0)
                filter.StoreId = storeId;
            return StoreApplicationManager.GetStoreApplicationsPage(filter, page, itemsPerpage);
            
        }

        /// <summary>
        /// 管理员获取小程序列表
        /// </summary>
        /// <param name="storeAppId">小程序编号</param>
        /// <param name="storeId">店铺编号</param>
        /// <param name="appId">小程序模板编号</param>
        /// <param name="devStatus">开发状态0:未知，1:待上传，2:已上传，3：待审核 4:审核结束，5:已发布</param>
        /// <param name="needUpdate">是否需要更新</param>
        /// <param name="page">当前页码</param>
        /// <param name="itemsPerPage">页码大小</param>
        /// <returns></returns>
        public Page<StoreApplication> AdminGetStoreApplicationPage(string storeAppId = "", string storeId = "", string appId = "", string devStatus = "",int needUpdate=-1, long page = 1,
            long itemsPerPage = 25)
        {
            var filter = new StoreApplicatioinFilter();
            var storeappid = 0;
            if (int.TryParse(storeAppId, out storeappid) && storeappid > 0)
                filter.StoreAppId = storeappid;
            var storeid = 0;
            if (int.TryParse(storeId, out storeid) && storeid > 0)
                filter.StoreId = storeid;
            var appid = 0;
            if (int.TryParse(appId, out appid) && appid > 0)
                filter.AppId = appid;
            var devstatus = -1;
            if (int.TryParse(devStatus, out devstatus) && devstatus > -1)
                filter.DevStatus = devstatus;
            if (needUpdate > -1)
                filter.NeedUpdate = needUpdate;
            return StoreApplicationManager.GetStoreApplicationsPage(filter, page, itemsPerPage);
        }
        /// <summary>
        /// 强制刷新票据
        /// </summary>
        /// <param name="storeAppId"></param>
        public void RefreshAuthorizerToken(int storeAppId)
        {
            StoreAppReleaseManager.RefreshAuthorizerToken(storeAppId, true);
        }

        ///// <summary>
        ///// 更新模板编号
        ///// </summary>
        ///// <param name="appid"></param>
        ///// <param name="templateId"></param>
        ///// <returns></returns>
        //public bool UpdateApplicationTemplateId(int appid, int templateId)
        //{
        //    if (templateId <= -1) throw new Exception("模板编号错误");
        //    WeApplicationManager.UpdateApplicationTemplate(appid, templateId);
        //    return true;
        //}
        /// <summary>
        /// 更新小程序案例的模板类型
        /// </summary>
        /// <param name="storeAppId">小程序案例ID</param>
        /// <param name="newAppId">新的模板ID</param>
        /// <returns></returns>
        public bool ChangeStoreApplicationId(int storeAppId, int newAppId)
        {
            var storeApp = StoreApplicationManager.GetStoreApplication(storeAppId);
            var app = WeApplicationManager.GetWeApplication(newAppId);
            if (storeApp == null)
                throw new Exception("未找到相关的小程序案例");
            if (app == null)
                throw new Exception("未找到相关的小程序模板");
            if (storeApp.AppId == newAppId)
                throw new Exception("选择的模板类型与现有相同，无需更改");
            if (storeApp.DevStatus != 5)
                throw new Exception("未发布的小程序，暂时不能更改模板");

            storeApp.AppId = app.AppId;
            storeApp.AuditId = 0;
            storeApp.AuditInfo = "";
            storeApp.DevStatus = 1;
            storeApp.TemplateId = app.TemplateId;
            storeApp.NeedUpdate = false;
            storeApp.UserTabBar = app.RawTabBar;
            StoreApplicationManager.UpdateStoreApplication(storeApp);
            return true;

        }
        /// <summary>
        /// 获取单个小程序实例信息
        /// </summary>
        /// <param name="storeAppId">实例ID</param>
        /// <returns></returns>
        public StoreApplication GetStoreApplication(int storeAppId)
        {
            return StoreApplicationManager.GetStoreApplication(storeAppId);
        }

        #endregion

        #region 上传小程序
        /// <summary>
        /// 上传小程序
        /// </summary>
        /// <param name="storeAppId">小程序实例ID</param>
        /// <returns></returns>
        public BaseResult CommitStoreApp(int storeAppId)
        {
            return StoreAppReleaseManager.CommitStoreApp(storeAppId);
        }
        #endregion

        #region 提交审核
        /// <summary>
        /// 提交审核
        /// </summary>
        /// <param name="storeAppId">小程序实例ID</param>
        /// <returns></returns>
        public BaseResult SubmitAudit(int storeAppId)
        {
            return StoreAppReleaseManager.SubmitAudit(storeAppId);

        }
        #endregion

        #region 发布上线
        /// <summary>
        /// 发布
        /// </summary>
        /// <param name="storeAppId">小程序实例ID</param>
        /// <returns></returns>
        public BaseResult ReleaseStoreApp(int storeAppId)
        {

            return StoreAppReleaseManager.ReleaseStoreApp(storeAppId);

        }
        #endregion

        #region 升级
        /// <summary>
        /// 升级小程序模板
        /// </summary>
        /// <param name="storeAppId">小程序实例ID</param>
        /// <returns></returns>
        public bool UpgradeStoreApp(int storeAppId)
        {
            return StoreAppReleaseManager.UpgradeStoreApp(storeAppId);
        }
        #endregion

        #region 预览
        /// <summary>
        /// 获取小程序的预览体验二维码地址
        /// </summary>
        /// <param name="storeAppId">小程序实例ID</param>
        /// <returns></returns>
        public string GetPreviewStoreAppUrl(int storeAppId)
        {
            return StoreAppReleaseManager.GetPreviewStoreAppUrl(storeAppId);
        }
        /// <summary>
        /// 添加新的体验者
        /// </summary>
        /// <param name="storeAppId">小程序实例ID</param>
        /// <param name="wechatId">微信号</param>
        /// <returns></returns>
        public BaseResult AddStoreAppPreviewUser(int storeAppId, string wechatId)
        {
            return StoreAppReleaseManager.AddStoreAppPreviewUser(storeAppId, wechatId);
        }
        #endregion

        #region 支付设置
        /// <summary>
        /// 获取支付设置
        /// </summary>
        /// <param name="storeAppId">小程序实例ID</param>
        /// <returns></returns>
        public StoreApplicationPaySetting GetPaySetting(int storeAppId)
        {
            var setting = StoreApplicationManager.GetStoreApplicationPaySetting(storeAppId) ?? new StoreApplicationPaySetting { StoreAppId = storeAppId };
            return setting;
        }
        /// <summary>
        /// 更新支付设置
        /// </summary>
        /// <param name="setting"></param>
        /// <returns></returns>
        public bool EditPaySetting(StoreApplicationPaySetting setting)
        {
            setting.MchId = setting.MchId ?? "";
            setting.MchKey = setting.MchKey ?? "";
            setting.PsbcMchId = setting.PsbcMchId ?? "";
            setting.PsbcMchKey = setting.PsbcMchKey ?? "";
            switch (setting.PayType)
            {
                case 0:
                    if (string.IsNullOrEmpty(setting.MchId))
                        throw new Exception("商户号不能为空");
                    if (string.IsNullOrEmpty(setting.MchKey))
                        throw new Exception("支付秘钥不能为空");
                    setting.CertPath = setting.CertPath ?? "";
                    break;
                case 1:
                    if (string.IsNullOrEmpty(setting.PsbcMchId))
                        throw new Exception("商户号不能为空");
                    if (string.IsNullOrEmpty(setting.PsbcMchKey))
                        throw new Exception("支付秘钥不能为空");
                    break;
            }

            if (setting.Id <= 0)
                StoreApplicationManager.AddStoreApplicationPaySetting(setting);
            else
                StoreApplicationManager.UpdateStoreApplicationPaySetting(setting);
            return true;
        }


        #endregion

        #region 页面配置
        /// <summary>
        /// 获取页面的配置信息
        /// </summary>
        /// <param name="storeAppId">小程序ID</param>
        /// <param name="path">页面的路径信息:pages/index/index</param>
        /// <returns></returns>
        public StoreAppPageSettingModel GetAppPageSetting(int storeAppId, string path)
        {
            return new StoreAppPageSettingModel
            {
                Path= "pages/index/index",
                StoreAppId=999,
                Title="关于-我们",
                ViewSetting=new ViewSetting { IsShowTab=false}
            };
        }

        #endregion

        #region 底部导航设置
        /// <summary>
        /// 获取店铺小程序的底部导航设置
        /// </summary>
        /// <param name="storeAppId"></param>
        /// <returns></returns>
        public TabBarPages GetStoreAppTabBarPages(int storeAppId)
        {
            var storeApp = StoreApplicationManager.GetStoreApplication(storeAppId);
            var tabbarJson = storeApp.UserTabBar;
            if (string.IsNullOrEmpty(storeApp.UserTabBar))
            {
                tabbarJson = WeApplicationManager.GetWeApplication(storeApp.AppId).RawTabBar;
                var rawTabBar = JsonConvert.DeserializeObject<TabBarPages>(tabbarJson);
                rawTabBar.backgroundColor = "#fff";
                rawTabBar.borderStyle = "white";
                rawTabBar.boxShadow = "0 0 6px 0";
                rawTabBar.color = "#6e6d6b";
                rawTabBar.selectedColor = "#e64340";
                var defaultTabbarJson = JsonConvert.SerializeObject(rawTabBar);
                storeApp.UserTabBar = defaultTabbarJson;
                tabbarJson = defaultTabbarJson;
                StoreApplicationManager.UpdateStoreApplication(storeApp);
            }

            var tabBar = JsonConvert.DeserializeObject<TabBarPages>(tabbarJson);
            if (tabBar == null)
                throw new ApiException(ExceptionCode.DataInvalid,"错误的配置文件");
            return tabBar;
        }

        #endregion

        #region FORMID
        /// <summary>
        /// 添加小程序表单ID
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="formId"></param>
        public void AddFormId(int uid, string formId)
        {
            var newFormId = new WeAppFormID
            {
                ExpiresIn=DateTime.Now.AddDays(7),
                FormId=formId,
                OpenId=OAuths.GetOAuthUserByUid(uid).OpenId,
                Uid=uid
            };
            WeAppFormIDManager.Add(newFormId);
        }


        #endregion

    }
}
